

package com.lzs.adx.commmon.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * 
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ValueOperations<String, String> valueOperations;
    @Autowired
    private HashOperations<String, String, Object> hashOperations;
    @Autowired
    private ListOperations<String, Object> listOperations;
    @Autowired
    private SetOperations<String, Object> setOperations;
    @Autowired
    private ZSetOperations<String, Object> zSetOperations;
    /**  默认过期时长，单位：秒 */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**  不设置过期时长 */
    public final static long NOT_EXPIRE = -1;

    public RedisUtils(RedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }


    public void set(String key, Object value, long expire){
        valueOperations.set(key, toJson(value));
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }



    public void hDel(String key, Object... fields){
        redisTemplate.opsForHash().delete(key, fields);
    }



    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public BoundSetOperations<String, Object> setCacheSet(final String key, final Set<String> dataSet)
    {
        BoundSetOperations<String, Object> stringObjectBoundSetOperations = redisTemplate.boundSetOps(key);
        Iterator<String> it = dataSet.iterator();
        while (it.hasNext())
        {
            stringObjectBoundSetOperations.add(it.next());
        }
        return stringObjectBoundSetOperations;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<Object> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }


    /**
     * 原子增操作
     *
     * @param key 键
     * @param delta 增量
     * @return 增加之后的值
     */
    public Long incr(String key) {
        return redisTemplate.opsForValue().increment(key);
    }


    /**
     *
     * @param key
     * @return
     */
    public Long incr(String key,long timeout) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();

        if ((null == increment || increment.longValue() == 0) ) {//初始设置过期时间
            entityIdCounter.expire(timeout, TimeUnit.HOURS);
        }
        return increment;
    }

    public Long atomicGet(String key){
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        return  entityIdCounter.get();
    }


    /**
     * 原子减操作
     *
     * @param key 键
     * @param delta 减量
     * @return 减少之后的值
     */
    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }



    public void hput(String key,String value,Object data){
        hashOperations.put(key,value,data);
    }

    public Object hget(String key,String value){
        Object o = hashOperations.get(key, value);
        return o;
    }


    public  Map<String, Object> hgetAll(String key){
        Map<String, Object> entries = hashOperations.entries(key);

        return entries;
    }




    public void set(String key, Object value){
        set(key, value, DEFAULT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = valueOperations.get(key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object){
        if(object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String){
            return String.valueOf(object);
        }
        return JSON.toJSONString(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz){
        return JSONObject.parseObject(json, clazz);
    }



    /**
     * 向 List 中添加元素
     *
     * @param key   List 的键
     * @param value List 中要添加的元素
     */
    public void addToList(String key, Object value) {
        listOperations.leftPush(key, value);
    }

    /**
     * 获取 List 中所有的元素
     *
     * @param key List 的键
     * @return List 中所有的元素
     */
    public List<Object> getList(String key) {
        Long size = listOperations.size(key);
        return listOperations.range(key, 0, size - 1);
    }



    /**
     * 从给定键对应的列表中移除所有等于给定值的元素。
     *
     * @param key   列表的键
     * @param value 要移除的值
     * @return 被移除的元素数量
     */
    public long removeValueFromList(String key, String value) {
        // 移除列表中所有等于value的元素
        return listOperations.remove(key, 0, value);
    }


    /**
     * 获取 List 中指定区间内的元素
     *
     * @param key   List 的键
     * @param start 区间的起始位置（包含）
     * @param end   区间的结束位置（包含）
     * @return 指定区间内的 List 元素
     */
    public List<Object> getList(String key, long start, long end) {
        return listOperations.range(key, start, end);
    }
}
